package com.cisp.business.simple;

/**
 * Author:LiuJunjie
 * Date:2025-09-03
 */
public class domain {

    public static void main(String[] args) {
        ClientZone clientZone = parseClientZone("191.168.0.0");
        System.out.println(clientZone);
        ClientZone xiaofang = parseClientZone("191.168.0.10");
        System.out.println(xiaofang);
    }

    public static ClientZone parseClientZone(String ipAddress) {
        String[] bizIps = null, officeIps = null;
        String value = "191.168.0.0/32";
        bizIps = value.split(",");
        value = "191.168.0.10/32";
        officeIps = value.split(",");

        if (bizIps != null) {
            for (String biz : bizIps) {
                if (isIpInRange(ipAddress, biz)) {
                    return ClientZone.BIZ;
                }
            }
        }

        if (officeIps != null) {
            for (String office : officeIps) {
                if (isIpInRange(ipAddress, office)) {
                    return ClientZone.OFFICE;
                }
            }
        }
        return ClientZone.UNKNOWN;
    }

    /**
     * 判断IP地址是否在指定的CIDR范围内
     *
     * @param ip   要检查的IP地址，格式为"xxx.xxx.xxx.xxx"
     * @param cidr CIDR表示的网络范围，格式为"xxx.xxx.xxx.xxx/xx"
     * @return 如果IP地址在指定范围内返回true，否则返回false
     */
    public static boolean isIpInRange(String ip, String cidr) {
        cidr = cidr.trim();
        // 解析IP地址为4个整数部分
        String[] ipArray = ip.split("\\.");
        int[] ipNums = new int[4];
        for (int i = 0; i < ipArray.length; i++) {
            ipNums[i] = Integer.parseInt(ipArray[i]);
        }

        // 解析CIDR格式的网络地址和前缀长度
        String[] cidrArray = cidr.split("/");
        String networkAddress = cidrArray[0];
        int prefixLength = Integer.parseInt(cidrArray[1]);

        // 解析网络地址为4个整数部分
        String[] networkArray = networkAddress.split("\\.");
        int[] networkNums = new int[4];
        for (int i = 0; i < networkArray.length; i++) {
            networkNums[i] = Integer.parseInt(networkArray[i]);
        }

        System.out.println(0xffffffffL);
        // 将IP地址转换为32位整数形式
        long ipNum = (ipNums[0] << 24) + (ipNums[1] << 16) + (ipNums[2] << 8) + ipNums[3];
        // 将网络地址转换为32位整数形式
        long networkNum = (networkNums[0] << 24) + (networkNums[1] << 16) + (networkNums[2] << 8) + networkNums[3];
        // 根据前缀长度生成子网掩码
        long mask = 0xffffffffL << (32 - prefixLength);

        // 通过按位与运算比较IP地址和网络地址是否在同一网段
        return (ipNum & mask) == (networkNum & mask);
    }

}
